Matrices
Matrices are very similar to vectors in Python, in fact you can use the same functions as you did to interact with vectors on matrices.
Once again we will be using the Numpy module, so make sure it is imported
import numpy as np
Writing matrices
The matrix $A=\begin{pmatrix}1&1 \newline 2&-1\end{pmatrix}$ can be written as
a = np.array([[1, 1], [2, -1]])
Try it out
```Interacting with matrices
Here is a reduced list of useful Numpy functions for matrices:
+
and-
can be used to add or subtract matrices*
can be used to multiply all terms within a matrix by a constant**
can be used to calculate the exponent of all terms within a matrix by a constantnp.dot(a,b)
calculate dot product of matrices a and bnp.linalg.inv(m)
calculate inverse of matrix mnp.transpose(m)
transpose a matrix mnp.linalg.det(m)
calculates the determinant of a matrix mnp.shape(m)
returns the dimensions of the matrix m
Solving linear equations with matrices
Let’s solve the following simultaneous linear equations with matrices in Python.
$\begin{align} x + y + z &= 7 \newline 2x -y + 2z &= 8 \newline 3x + 2y -z &= 11 \end{align}$
We can write the following code to solve this:
import numpy as np
A = np.array([[1, 1, 1], [2, -1, 2], [3, 2, -1]])
b = np.array([[7], [8], [11]])
x = np.dot(np.linalg.inv(A), b)